package com.bw.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * 注意事项：
 *  自定义的 过滤器的名称 要和
 *     - MyParam=name
 *  MyParamGatewayFilterFactory 来命名 过滤器的名称
 * @author wlz
 */
@Component
public class MyParamGatewayFilterFactory extends AbstractGatewayFilterFactory<MyParamGatewayFilterFactory.ParamConfig> {

    private static final String PARAM_NAME="param";

    public MyParamGatewayFilterFactory() {
        super(ParamConfig.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(PARAM_NAME);
    }


    @Override
    public GatewayFilter apply(ParamConfig config) {
        return (exchange,chain)->{
            //获取请求对象
            ServerHttpRequest request = exchange.getRequest();

            //判断请求参数中是否有NAME_KEY
            if(request.getQueryParams().containsKey(config.param)){
                //参数返回的是个集合
                List<String> strings = request.getQueryParams().get(config.param);
                //遍历
                strings.forEach(value->{
                    System.out.printf("-------%s=%s----",config.param,value);
                    System.out.println(config.param+"="+value);
                });
            }
            return chain.filter(exchange);
        };

     /*   return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                return chain.filter(exchange);
            }
        };*/
    }

    public static class ParamConfig {
        protected String param;
        public void setParam(String param) {
            this.param = param;
        }
        public String getParam() {
            return param;
        }
    }
}
